package com.example.mingyue.utils;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.Map;

/**
 * 后端发起对第三方接口的请求
 * 主要用于获取微信openid
 */
public class HttpClientUtils {

    /**
     * 发送get请求带参数
     *
     * @param url
     * @return
     */
    public static String getRequest(String url, Map<String, String> map){
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String result = "";
        CloseableHttpResponse response = null;
        //发送请求
        try {
            //2.创建封装的URI对象，可以存放参数

            URIBuilder uri = new URIBuilder(url);
            if (map != null) {
                for (String key : map.keySet()){
                  //  key是键，map.get(key)是获取的值
                    uri.addParameter(key, map.get(key));
                }
            }

            //创建GET请求
            HttpGet httpGet = new HttpGet(uri.build());

            response = httpClient.execute(httpGet);

            //如果响应成功，就可以返回信息
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //无论前面是否成功，这里都要关闭资源
            try {
                httpClient.close();
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }
}
